package com.xiaoyao.novel.parser;

import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.apache.log4j.Logger;

import com.xiaoyao.novel.crawl.BaseCrawl;
import com.xiaoyao.novel.pojo.Book;
import com.xiaoyao.novel.pojo.Chapter;
import com.xiaoyao.novel.util.ClassUtil;
import com.xiaoyao.novel.util.FileUtil;

public class ShuhuangParser {
	private static Logger logger = Logger.getLogger(ShuhuangParser.class);

	/**
	 * 作者,[书名],简介,[类型],图片
	 * 
	 * @param page
	 * @param book
	 * @return
	 */
	public static Book parseDescrib(String page, Book book) {
		page = page.replaceAll("\"", "'");
		page = page.replaceAll("&nbsp;", " ");
		page = page.replaceAll("\\s+", " ");
		logger.debug(page);
		String infoRegex = "<div id='maininfo'>.+?<h1>(.+?)</h1>.+?<p>作\\s*者：(.+?)</p>.+?<div id='intro'>(.+?)</div>"
				+ ".+?<img.+?src='(.+?)'";
		Pattern infoPattern = Pattern.compile(infoRegex);
		Matcher matcher = infoPattern.matcher(page);
		if (matcher.find()) {
			if (ClassUtil.isEmpty(book.picPath)) {
				String picUrl =  matcher.group(4);
				String fileName = book.bookId + ".jpg";
				fileName = BaseCrawl.downLoadImage(picUrl, fileName); // 抓图片
				book.picPath = FileUtil.PIC_DIR + fileName;
			}
			String authorName = matcher.group(2);
			book.setAuthorName(authorName);
			if (ClassUtil.isEmpty(book.describ)) {
				String describ = matcher.group(3);
				book.setDescrib(describ);
			}
		} else {
			logger.error("信息错误!");
		}
		return book;
	}

	public static List<Chapter> parseBook(String page, Book book) {
		logger.debug("开始解析...");
		page = page.replaceAll("\"", "'");
		page = page.replaceAll("\\s+", " ");
		 
		List<Chapter> list = new ArrayList<Chapter>();
		book.list = list;
		String bookRegex = "<dd><a href='((\\d+).+?)'>(.+?)</a></dd>";
		Pattern bookPattern = Pattern.compile(bookRegex);
		Matcher matcher = bookPattern.matcher(page);
		while (matcher.find()) {
			String title = matcher.group(3).trim();
			logger.debug(title);
		 		Chapter chapter = new Chapter();
				list.add(chapter);
				chapter.bookId = book.bookId;
				chapter.chapterUrl = book.bookUrl  + matcher.group(1);
				chapter.webId = matcher.group(2);
				chapter.chapterTitle = title;
				logger.debug(chapter); 
		}
		return list;
	}

	public static void parseChapter(String page, Chapter chapter) {
		page = page.replaceAll("\"", "'");
		page = page.replaceAll("\\s+", " ");
		logger.debug(page);
		String chapterRegex = "<div id='content'>(.+?)</div>";
		Pattern chapterPattern = Pattern.compile(chapterRegex);
		Matcher matcher = chapterPattern.matcher(page);
		if (matcher.find()) {
			chapter.chapterContent = matcher.group(1);
			logger.debug(chapter.chapterContent);
		}
	}
}
